
package VLSys;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import DBConnection.*;
import java.sql.*;
import VLSObjects.*;

import javax.swing.table.DefaultTableModel;

public class ManagementVehicleEdit extends JPanel{
    
    JComboBox manufacturer;
    JComboBox size;
    JTextField model;
    JTextField vehicleID;
    String[] manufacturerChoices = { "", "Audi", "BMW", "Chevrolet", "Chery", "Chrysler", "Ferrari", "Ford", "Honda", "Hyundai", "Isuzu", "Jaguar", "Lamborghini", "Land Rover", "Lexus","Mazda","Mercedes-Benz","Mitsubishi","Nissan","Pilipinas Hino","Porsche","SsangYong","Subaru","Suzuki","Toyota","Volvo","Others"};
    String[] sizeChoices = { "", "Small", "Medium","Large"};
    JButton submitButton;
    JButton cancelButton;
    JButton getButton;
    JButton editVehicleButton;
    JButton deleteButton;
    JLabel vehicleIDLabel;
    JLabel vehicleManufacturerLabel;
    JLabel vehicleModelLabel;
    JLabel vehicleSizeLabel;
    JLabel editVehicleLabel;
    JScrollPane vehicleScroll;
    JTable vehicleTable;
    
    JTextField filter;
    JLabel filterLabel;
    /*
    ImageIcon ask_red = new ImageIcon("images/prompt_ask.png");
    ImageIcon notice = new ImageIcon("images/prompt_notice.png");
    */
    
    ImageIcon notice_green = new ImageIcon("images/prompt_notice_green.png");
    ImageIcon ask_red = new ImageIcon("images/prompt_ask_red.png");
    ImageIcon notice_red = new ImageIcon("images/prompt_notice_red.png");
    
    DefaultTableModel model1;
    int enable = 1;
    
    int x = -1;    
    Object headers[] = {"Vehicle Type ID", "Manufacturer", "Model", "Size"};
    Object dummyData[][] = {{"veh001", "Sarao", "ExpressCarabao100", "L"},
                        {"veh002", "Pilipinas Hino", "Bus Ranger", "L"}};
    
    String blank = "";
    String string[] = new String[5];
    
    public ManagementVehicleEdit(final JFrame frame)
    {
        
        setVisible(false);
        setLayout(null);
        setBackground(null);
        
        filterLabel = new JLabel("Search:");
        filterLabel.setBounds(394,390,150,20);
        
        filter = new JTextField();
        filter.setBounds(439,390,150,20);
        filter.setBorder(null);
        
               
        model = new JTextField();
        vehicleID = new JTextField();
        manufacturer = new JComboBox(manufacturerChoices);
        size = new JComboBox(sizeChoices);
        
       
        getButton = new JButton();
        submitButton = new JButton();
        cancelButton = new JButton();
        editVehicleButton = new JButton();
        deleteButton = new JButton();
        
        
        vehicleIDLabel = new JLabel("Vehicle ID:");
        vehicleManufacturerLabel = new JLabel("Manufacturer:");
        vehicleModelLabel = new JLabel("Model:");
        vehicleSizeLabel = new JLabel("Size:");
        editVehicleLabel = new JLabel("EDIT VEHICLE");
        
        editVehicleLabel.setFont(new Font("sansserif", Font.PLAIN, 40));
        
        editVehicleLabel.setBounds(10,10,300,30);
        
        vehicleIDLabel.setBounds(59, 50, 150, 20);
        vehicleManufacturerLabel.setBounds(39,75,150,20);
        vehicleModelLabel.setBounds(82,100,150,20);
        vehicleSizeLabel.setBounds(92,125,150,20);
       
        vehicleID.setBounds(130,50,200,20);
        manufacturer.setBounds(130,75,200,20);
        model.setBounds(130,100,200,20);
        size.setBounds(130,125,200,20);
        
        vehicleID.setBorder(null);
        manufacturer.setBorder(null);
        model.setBorder(null);
        size.setBorder(null);
        
        getButton.setText("Get");
        submitButton.setText("Submit");
        cancelButton.setText("Clear");
        editVehicleButton.setText("Edit");
        deleteButton.setText("Delete");
        
        getButton.setBounds(340,50, 75, 20);
        submitButton.setBounds(175,150,75,20);
        cancelButton.setBounds(255,150,75,20);
        editVehicleButton.setBounds(15, 390, 75, 20);
        deleteButton.setBounds(93, 390, 75, 20);
        
        //table codes
        
        vehicleTable = new JTable();
        vehicleTable.setModel(new javax.swing.table.DefaultTableModel(null, headers
        ) {


            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        });
        
        model1 = (DefaultTableModel)vehicleTable.getModel();
        vehicleScroll = new JScrollPane();
        vehicleTable.getTableHeader().setReorderingAllowed(false);
        vehicleScroll.setViewportView(vehicleTable);
        vehicleScroll.setBounds(15, 240, 575, 150);
        
        vehicleTable.getTableHeader().setResizingAllowed(false);
        
        model.setEnabled(false);
        vehicleID.setEditable(false);
        vehicleID.setEnabled(false);
        manufacturer.setEnabled(false);
        size.setEnabled(false);
        submitButton.setEnabled(false);
                
        disableButton();
        
        add(vehicleID);
        add(manufacturer);
        add(model);
        add(size);
        add(editVehicleButton);
        add(submitButton);
        add(cancelButton);
        add(deleteButton);
        add(vehicleIDLabel);
        add(vehicleManufacturerLabel);
        add(vehicleModelLabel);
        add(vehicleSizeLabel);
        add(editVehicleLabel);
        add(vehicleScroll);
        add(filter);
        add(filterLabel);
        
        populateTable("SELECT * FROM vehiclelist ORDER BY vehicleID");
        
        filter.addKeyListener(new KeyAdapter() {
          public void keyReleased(KeyEvent e) {
              
              if (e.getKeyCode()==39 || e.getKeyCode()==37)
        {
               
        }
              else 
                filter.setText(capitalizeFirstLetters(filter.getText()));
     
          
          
          populateTable("SELECT * FROM vehiclelist WHERE model LIKE '" + filter.getText() + "%' ORDER BY model ASC");
          
          }

          public void keyTyped(KeyEvent e) {
          }

          public void keyPressed(KeyEvent e) {
          }
        });
        
        model.addKeyListener(new KeyAdapter() {
          public void keyReleased(KeyEvent e) {

                 if (e.getKeyCode()==39 || e.getKeyCode()==37)
        {
               
        }
              else 
                   model.setText(capitalizeFirstLetters(model.getText()));
          }
          public void keyTyped(KeyEvent e) {
              
          }

          public void keyPressed(KeyEvent e) {
              
          }
        });
        
        vehicleTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                TableMouseClicked(evt);
            }
            });
        
        editVehicleButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
               if(x != -1)
                    enableButton();
                else
                    JOptionPane.showMessageDialog(frame,
                                        "Please Select Vehicle",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
            }
        }
        );
        
         deleteButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                    VehicleManager newVm = new VehicleManager();
                    boolean result = false;
                    int n = 20;
                    
                if(x != -1)
                {
                    n = JOptionPane.showConfirmDialog(
                            frame,
                            "Are You Sure?",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            ask_red);
                    if(n==0)
                    {
                        result = newVm.deleteVehicle(vehicleID.getText());
                               if (result == true)
                                    JOptionPane.showMessageDialog(frame,
                                            "Vehicle Deleted.",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_red);
                               model1.setRowCount(0);
                               populateTable("SELECT * FROM vehiclelist ORDER BY vehicleID");
                    }
                }    
                else
                    JOptionPane.showMessageDialog(frame,
                                        "Please Select Vehicle to Delete",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                
                
            }
        }
        );
        
        submitButton.addActionListener(new  ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {
                

                string[0] = (String)manufacturer.getSelectedItem();
                string[1] = model.getText();
                string[2] = (String)size.getSelectedItem();
                
                if(string[0].length() == 0 && string[1] == blank && string[2].length() == 0 )
                {
                    checkEmpty();
                    JOptionPane.showMessageDialog(frame,
                                        "Incomplete Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);
                    
                } 
                else if(string[1].length()== 0 || string[0] == blank || string[2] == blank )
                {
                    checkEmpty();
                    
                        if(string[1].length() > 25)
                        {
                            checkEmpty();
                            JOptionPane.showMessageDialog(frame,
                                                "Invalid and Incomplete Input",
                                                "Vehicle Logging Service",
                                                JOptionPane.WARNING_MESSAGE,
                                                notice_red);

                        }    
                   
                        else if(string[1].length() == 0 || string[0] == blank || string[2] == blank)
                        JOptionPane.showMessageDialog(frame,
                                            "Incomplete Input",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_red);
                     
                     
                    
                }   
                else if(string[1].length() > 25)
                {
                    checkEmpty();
                    JOptionPane.showMessageDialog(frame,
                                        "Invalid Input",
                                        "Vehicle Logging Service",
                                        JOptionPane.WARNING_MESSAGE,
                                        notice_red);

                     
                }            
                else if(string[1].length() <= 25 && string[0] != blank && string[2] != blank)   
                {
                    int n = JOptionPane.showConfirmDialog(
                            frame,
                            "Proceed with current values?",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            ask_red);
                    
                    if(n==0)
                    {
                        Vehicle editVehicle = new Vehicle();
                        VehicleManager newVm = new VehicleManager();
                        
                        
                        editVehicle.setManufacturer(string[0]);
                        editVehicle.setModel(string[1]);
                        editVehicle.setSize(string[2]);
                        editVehicle.setVehicleID(vehicleID.getText());
                        
                        boolean existing = newVm.checkVehicle(string[0], string[1], editVehicle.getVehicleID());
                       
                        if(existing == true)
                           {    JOptionPane.showMessageDialog(frame,
                                            "Vehicle record already exists!",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_red);
                           }
                        
                        else
                        {
                            boolean result = newVm.editVehicle(editVehicle);
                            if (result == true)
                                    JOptionPane.showMessageDialog(frame,
                                            "Vehicle Record Edited.",
                                            "Vehicle Logging Service",
                                            JOptionPane.WARNING_MESSAGE,
                                            notice_green);
                            model1.setRowCount(0); 
                            /*while (model1.getRowCount()>0){
                                    model1.remove(0);
                                    }*/
                            disableButton();
                            populateTable("SELECT * FROM vehiclelist ORDER BY vehicleID");
                            resetValues();
                            x=-1;
                        }
                    
                    }
                            
                            
                       else
                            {  System.out.print("ayaw!");

                            }
                }
            }
        }
        );
        
        cancelButton.addActionListener(new  ActionListener()
       {
       public void actionPerformed(ActionEvent e)
            {
               int n = JOptionPane.showConfirmDialog(
                            frame,
                            "Are you sure you want to clear the values?",
                            "Vehicle Logging Service",
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.QUESTION_MESSAGE,
                            ask_red);
               if(n==0)
                    { 
                resetValues();
                
                disableButton();
                x=-1;
                    }
            }
        }
        );
        
    }
    
    public void disableButton()
        {
            
            model.setEnabled(false);
            manufacturer.setEnabled(false);
            size.setEnabled(false);
            cancelButton.setEnabled(false);
            submitButton.setEnabled(false);
            editVehicleButton.setEnabled(true);
            enable = 1;
        }
        
    public void enableButton()
        {
            
            model.setEnabled(true);
            manufacturer.setEnabled(true);
            size.setEnabled(true);
            cancelButton.setEnabled(true);
            submitButton.setEnabled(true);
            editVehicleButton.setEnabled(false);
            enable = 0;
        }
        
    public void checkEmpty()
    {   
        String s = "";
       
        if((String)manufacturer.getSelectedItem() == s)
            manufacturer.setBackground(Color.YELLOW);
        
        if((String)manufacturer.getSelectedItem() != s)
            manufacturer.setBackground(null);
        
        if(model.getText().length() == 0)
            model.setBackground(Color.YELLOW);
               
        else if(model.getText().length() > 25)
            model.setBackground(Color.RED);
        
        else if(model.getText().length() <= 25)
            model.setBackground(null);
        
        if((String)size.getSelectedItem() == s)
            size.setBackground(Color.YELLOW);
        
                
        if((String)size.getSelectedItem() != s)
            size.setBackground(null);
        
    }
        
        public void resetValues()
        {

                    manufacturer.setBackground(null);
                    model.setBackground(null);
                    size.setBackground(null);
                    disableButton();
                    manufacturer.setSelectedItem("");
                    model.setText("");
                    size.setSelectedItem("");
                    x = -1;

        }
        
         private void TableMouseClicked(java.awt.event.MouseEvent evt) 
           {                                     
               int rowSelected = vehicleTable.getSelectedRow();
                
               if(enable == 1)
               {
                    x = rowSelected;
                    
                    int vID = (Integer)model1.getValueAt(x, 0);
                    
                    //model1.get
                    vehicleID.setText(Integer.toString(vID));
                    manufacturer.setSelectedItem((String)model1.getValueAt(x, 1));
                    model.setText((String)model1.getValueAt(x, 2));
                    size.setSelectedItem((String)model1.getValueAt(x, 3));
                   
               }

            }
         
         public void populateTable(String pS){
             
              try{
                    //opens db connection
                    ConnectionFactory myFactory = ConnectionFactory.getFactory();
                    Connection conn = myFactory.getConnection();

                    //SQL Query
                    PreparedStatement pstmt = conn.prepareStatement(pS);

                    //execute query
                    ResultSet rs = pstmt.executeQuery();
                    
                    model1.getDataVector().removeAllElements();
                    vehicleTable.setAutoCreateRowSorter(true);

                    //populate JTable 
                    while(rs.next()){
                    model1.addRow(new Object[]{rs.getInt(1), rs.getString(2), rs.getString(3), rs.getString(4)});
                    model1.fireTableDataChanged();
                    }
                    
                    //close DB connection
                    conn.close();
                }
                      
                catch(SQLException e)
                {
                   e.printStackTrace();
                   System.out.print("ayaw!");
                }
             
          }
         
         public static String capitalizeFirstLetters ( String s ) {

        for (int i = 0; i < s.length(); i++) {

            if (i == 0) {
                // Capitalize the first letter of the string.
                s = String.format( "%s%s",
                             Character.toUpperCase(s.charAt(0)),
                             s.substring(1) );
            }

            // Is this character a non-letter or non-digit?  If so
            // then this is probably a word boundary so let's capitalize
            // the next character in the sequence.
            if (!Character.isLetterOrDigit(s.charAt(i))) {
                if (i + 1 < s.length()) {
                    s = String.format( "%s%s%s",
                                 s.subSequence(0, i+1),
                                 Character.toUpperCase(s.charAt(i + 1)),
                                 s.substring(i+2) );
                }
            }

        }

        return s;

    }
    
}
